#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author : 刘宇
# date : 2018/5/23
import time,re,os
from subprocess import Popen, PIPE
import logging
import paramiko,json
# logger = logging.getLogger('script')


def default_result():
    return {'exit_code': '99', 'return_info': 'Failed to run, function_name is not existed'}


class SSHConnection(object):
    def __init__(self, host, port, username, password):
        self._host = host
        self._port = port
        self._username = username
        self._password = password
        self._transport = None
        self._sftp = None
        self._client = None
        self._connect()

    def _connect(self):
        transport = paramiko.Transport((self._host, self._port))
        transport.connect(username=self._username, password=self._password)
        self._transport = transport

    #下载
    def download(self, remotepath, localpath):
        if self._sftp is None:
            self._sftp = paramiko.SFTPClient.from_transport(self._transport)
        self._sftp.get(remotepath, localpath)
        self.close()


    #上传
    def put(self, localpath, remotepath):
        if self._sftp is None:
            self._sftp = paramiko.SFTPClient.from_transport(self._transport)
        self.exec_command('mkdir -p %s'%(os.path.dirname(remotepath)))
        self._sftp.put(localpath, remotepath)
        self.close()

    #执行命令
    def exec_command(self, command):
        if self._client is None:
            self._client = paramiko.SSHClient()
            self._client._transport = self._transport
        stdin, stdout, stderr = self._client.exec_command(command)
        # print(" {} : {}".format( stdout.read(), stderr.read()))

        err = stderr.read()
        data = stdout.read()
        if len(err) > 0:
            return {'status':1,'infos':err}

        if len(data) > 0:
            return {'status':0,'infos':data}
        return {'status': 0, 'infos': data}

    def close(self):
        if self._transport:
            self._transport.close()
        if self._client:
            self._client.close()

def shell_command(cmdstrs):
    cmdresult = re.split(r'\s+', cmdstrs)
    result = default_result()
    result['return_info'] = ''
    shell_start_time = time.time()
    child = Popen(cmdresult, shell=True, stdout=PIPE, stderr=PIPE)
    out, err = child.communicate()
    shell_end_time = time.time()
    result['shell_run_time'] = shell_end_time - shell_start_time
    out = out.strip(b'\n')
    result['return_info'] = out
    result['exit_code'] = child.returncode
    logging.info(u'shell: %s - %s%s - %s%d' % (cmdstrs, 'return_info: ', out, 'exit_code: ', child.returncode))
    return result




def use_user_pass(hostip,port,user,passwd,cmdstrs):
    result = default_result()
    try:
        conn = SSHConnection(hostip, port, user, passwd)
    except Exception as e:
        return [{hostip: {
            'message': str(e),
            'code': 1,
            'results':{}
        }}]
    result['return_info'] = ''
    shell_start_time = time.time()
    # print(cmdstrs)
    out = conn.exec_command(cmdstrs)
    shell_end_time = time.time()
    result['shell_run_time'] = shell_end_time - shell_start_time
    outs = str(out['infos'], 'utf-8')
    outs = outs.strip('\n')
    result['return_info'] = outs
    result['exit_code'] = out['status']
    # logging.info(u'shell: %s - %s%s - %s%d' % (cmdstrs, 'return_info: ', out, 'exit_code: ', out['status']))
    logging.info('host: %s user:%s - shell: %s - %s%s - %s%d' % (
    hostip, user, cmdstrs, 'return_info: ', out, 'exit_code: ', out['status']))
    conn.close()

    return [{hostip: {
        'message': True,
        'code': 0,
        'results':{
            'message': outs,
            'code': out['status'],
            'shell_run_time':shell_end_time - shell_start_time
        }
    }}]


# print(use_user_pass( "10.1.41.200",6554,"root","root","mkdir /r/d/a/d"))